import { Injectable } from "@nestjs/common";
import { UserService } from "../user/user.service";
import { JwtService } from "@nestjs/jwt";
import { JwtPayload } from "src/utils/interfaces/jwt.interface";
import { ConfigService } from "nestjs-config";
import { createHmac } from "crypto";

@Injectable()
export class AuthService {
  constructor(
    private readonly usersService: UserService,
    private readonly jwtService: JwtService,
    private readonly config: ConfigService
  ) {}

  // 验证 username 和 password 是否符合存储的数据
  async validateUser(username: string, pass: string): Promise<any> {
    // 找到对应 username 的 user
    const user = await this.usersService.findByUsername(username);
    pass = createHmac("sha256", this.config.get("express.password") ?? "secret")
      .update(pass)
      .digest("hex");
    // check 一下 password
    if (user && user.password === pass) {
      // 返回一些信息
      return { id: user.id, role: user.role, companyId: user.company?.id };
    }
    return null;
  }

  // 获得user,并且将该user注册到jwtService中
  async login(user: {
    id: string;
    role?: "admin" | "manager";
    companyId: string;
  }) {
    const payload: JwtPayload = {
      sub: user.id,
      aud: user.role,
      company: user.companyId,
    };
    return {
      access_token: this.jwtService.sign(payload),
    };
  }
}
